package com.wangrui.controller;



import com.wangrui.dto.NewRole;
import com.wangrui.utils.Page;
import com.wangrui.dto.UserSchool;
import com.wangrui.pojo.Role;
import com.wangrui.pojo.School;
import com.wangrui.pojo.User;
import com.wangrui.pojo.UserRole;
import com.wangrui.service.RoleService;
import com.wangrui.service.SchoolService;
import com.wangrui.service.UserRoleService;
import com.wangrui.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.*;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 王锐
 * @since 2020-07-04
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private SchoolService schoolService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserRoleService userRoleService;

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String login(HttpSession session, User user, Model model) {
        List<User>  user1 =  userService.queryAllUser();
        User u = userService.login(user);
        if (u != null) {
            session.setAttribute("user", u);
            School school = schoolService.getSchoolName(u.getSid());
            session.setAttribute("school", school);
            model.addAttribute("msg", "ok");
            return "redirect:/main.html";
        }
        model.addAttribute("msg", "登录失败!用户名或密码错误。");
        return "/login";

    }

    @RequestMapping("/userQueryJson")
    @ResponseBody
    public List<User> userQueryJson(){
        List<User> list = userService.userQueryJson();
        return list;
    }

    @RequestMapping("/queryAllUser")
    public ResponseEntity< Map<String, Object>> queryAllUser(
            @RequestParam("keyword")String keyword,
            @RequestParam("page")int page,
            @RequestParam("rows")int rows
    ){
        Map<String, Object> map = new HashMap<>();
        Page<UserSchool> page1 = new Page<>();
        page1.setPageSize(rows);
        page1.setPageIndex(page);
        page1.setKeyword(keyword);


        int total = userService.getTotal();
        List<UserSchool> userSchools = userService.getUserSchool(page1);
        userSchools.forEach(System.out::println);

        map.put("rows",userSchools);
        map.put("total",total);
        return ResponseEntity.ok(map);


    }
    /**
    * @Description:  查询角色，得到所有角色集合List<Role>，新建角色（新增字段selected），
     * 遍历集合List<Role>，判断角色id与传入的id是否相同，相同添加selected为true
    * @Param: [id]
    * @return: org.springframework.http.ResponseEntity<java.util.List<com.wangrui.pojo.Role>>
    * @Author: 王锐
    * @Date: 2020/7/7
    */
    @RequestMapping(value = "/queryAllRolesById")
    public ResponseEntity<List<NewRole>> queryAllRolesById( @RequestParam("id")int user_id,HttpSession session) {
        List<Role> listRole = roleService.queryAllRolesById();
        List<NewRole> objects = new ArrayList<>();
        //通过角色id查询角色用户表
        UserRole userRoles = userRoleService.queryUserRoleByUserId(user_id);
        for (Role role : listRole) {
            NewRole newRole = new NewRole();
            if (userRoles != null) {
                if (role.getRoleId()==userRoles.getRoleid()){
                    newRole.setSelected(true);
                }
            }
            newRole.setRoleId(role.getRoleId());
            newRole.setRoleName(role.getRoleName());
            objects.add(newRole);
        }
        return ResponseEntity.ok(objects);
    }


    /**
    * @Description:  更新角色权限,selected为
    * @Param: []
    * @return: org.springframework.http.ResponseEntity<java.lang.Void>
    * @Author: 王锐
    * @Date: 2020/7/8
    */
    @RequestMapping(value = "/saveroles")
    public ResponseEntity<Void> queryAllRolesById(
            @RequestParam("id") int user_id,
            @RequestParam("roles") int[] roles) {
        UserRole userRoles = userRoleService.queryUserRoleByUserId(user_id);
        UserRole userRole = new UserRole();
        for (int role_id : roles) {
            if (userRoles==null){
                //newRole==null 执行添加
                userRole.setUserid(user_id);
                userRole.setRoleid(role_id);
                userRoleService.addUserRole(userRole);
            }else{
                //newRole!=null 执行更新
                userRole.setId(userRoles.getId());
                userRole.setUserid(user_id);
                userRole.setRoleid(role_id);
                userRoleService.updateUserRole(userRole);
            }
        }

        return  new ResponseEntity<>(HttpStatus.CREATED);
    }


    @RequestMapping("/saveUser")
    public ResponseEntity<Void> saveUser(User user)  {
        userService.saveUser(user);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @RequestMapping("/updateUser")
    public ResponseEntity<Void> updateUser(User user)  {
        userService.updateUser(user);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @RequestMapping("/deleteUserByIds")
    @ResponseBody
    public String deleteUserByIds(@RequestParam("ids") int ids)  {
        userService.deleteUserByIds(ids);
        return "ok";
    }

    @RequestMapping("/verifyUsername")
    @ResponseBody
    public Boolean verifyUsername(@RequestParam("username") String username)  {
        Boolean b = userService.queryUserByUserName(username);
        return b;
    }

    @RequestMapping("/save")
    public String saveHtml()  {
        return "user/save";
    }

    @RequestMapping("/update")
    public String updateHtml()  {
        return "user/update";
    }

    @RequestMapping("/list")
    public String listHtml()  {
        return "user/userlist";
    }

    @RequestMapping("/setroles")
    public String setrolesHtml()  {
        return "user/setroles";
    }










}

